<template>
  <div class="box2">
    <div class="header">
      <img :src="user.img" alt="" />
      <h4>{{ user.name }}</h4>
    </div>
    <div class="content">
      <div v-for="(msg, index) in msgs" :key="index" .class="msg.id == user.id ? 'right' : 'left'">
        <message :msg="msg" :order="msg.id == user.id ? 'order1' : 'order0'"></message>
      </div>
    </div>
    <div class="footer">
      <input type="text" v-model="msg" @keyup.enter="sendMsg" />
      <button @click="sendMsg" class="btn btn-success">发送</button>
      <audio :src="qqSound" hidden ref="qqSound"></audio>
    </div>
  </div>
</template>

<script>
import emitter from '@/utils/mitt'
import Message from './Message.vue'
import qqSound from '@/assets/audio/preview.mp3'
export default {
  components: {
    Message,
  },
  /**
   * user:{name.img,friend}
   */
  props: ['user'],
  data() {
    return {
      msg: '',
      msgs: [],
      qqSound: qqSound,
    }
  },

  mounted() {
    emitter.on('send_' + this.user.id, this.receeiveMsg)
  },

  methods: {
    sendMsg() {
      const message = { msg: this.msg, id: this.user.id, img: this.user.img }
      this.msgs.push(message)
      emitter.emit('send_' + this.user.friend, message)
      this.$refs.qqSound.play()
    },
    receeiveMsg(msg) {
      this.msgs.push(msg)
    },
  },
}
</script>

<style lang="scss" scoped>
.box2 {
  display: flex;
  flex-direction: column;
  width: 500px;
  min-height: 500px;
  max-height: 90vh;
  border: 1px solid blue;
  margin-bottom: 20px;
}
.header {
  width: 100%;
  border-bottom: 1px solid gray;
  display: flex;
  justify-self: center;
  align-items: center;
  height: 50px;
  img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
  }
}
.content {
  flex: 1;
  width: 100%;
  display: flex;
}
.footer {
  width: 100%;
  border-top: 1px solid gray;
  display: flex;
  height: 50px;
  input {
    //width: 100%;
    border: none;
    background: none;
    outline: none;
    padding-left: 10px;
    flex: 1;
  }
  button {
    width: 60px;
  }
}
.left {
  display: flex;
  justify-content: start;
}
.right {
  display: flex;
  width: 100%;
  justify-content: end;
}
</style>
